var subSocket;

function initWebSocket(url, headerMsg, onMessageFunction) {
    var request = {
        // _rootPath + "/websocket/chat"
        url: url,
        contentType: "application/json",
        transport: 'websocket',
        logLevel: 'error',
        reconnectInterval: 5000,
        fallbackTransport: 'long-polling',
        headers: headerMsg
    };

    // 连接打开时
    request.onOpen = function (response) {
        console.log("打开了websocket连接：" + response);
    };

    // 重新连接时
    request.onReconnect = function (request, response) {
        console.log("websocket重新连接：" + response);
    };

    // 收到推送消息时
    request.onMessage = function (response) {
        // message 即为收到的消息内容
        var message = response.responseBody;
        try {
            if (typeof onMessageFunction == 'function') {
                var obj = JSON.parse(message);
                onMessageFunction(true , obj.name , obj.message);
            }
        } catch (e) {
            console.log('Error: ', message);
            return;
        }
    };

    // 发生错误时
    request.onError = function (response) {
    };

    if (!subSocket) {
        subSocket = atmosphere.subscribe(request);
    }
}
